package com.soriya.nestlive.im;

import com.alibaba.fastjson.JSONObject;
import com.soriya.nestlive.constant.CommonConst;
import com.soriya.nestlive.entity.ChannelEntity;
import com.soriya.nestlive.im.constant.MessageType;
import com.soriya.nestlive.im.message.IMMessage;
import com.soriya.nestlive.service.ChannelService;
import com.soriya.nestlive.service.LiveService;
import com.soriya.nestlive.util.RedisUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ChannelHandler.Sharable
public class LiveChatHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private LiveService liveService;

    @Autowired
    private ChannelService channelService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("{} 连接成功", ctx.channel().remoteAddress());
        String message = IMMessage.systemMessageToString("Welcome come to NestLive");
        ctx.channel().writeAndFlush(message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        IMMessage<?> message = JSONObject.parseObject(msg.toString(), IMMessage.class);

        if (MessageType.GROUP_SIGN.equals(message.getType())) {
            // 加入直播间
            Long to = message.getTo();
            log.info("{} Add {}", ctx.channel().remoteAddress(), to);
            String tip = "欢迎来到直播间!直播间内严禁出现违法违规、低俗色情、吸烟酗酒、人身伤害等内容。如主播再直播过程中以不正当方式诱导、私下交易，请谨慎判断，以防人身财产损失。请大家注意财产安全，理性消费，谨防网络诈骗。";
            ctx.channel().writeAndFlush(IMMessage.systemMessageToString(tip));
            ChannelRepository.addGroup(to, ctx.channel());
        }

        if (MessageType.GROUP_MESSAGE.equals(message.getType())) {
            // 直播间消息
            Long to = message.getTo();
            ChannelGroup channelGroup = ChannelRepository.getChannelGroup(to);
            System.out.println("Size: " + channelGroup.size());

            channelGroup.writeAndFlush(JSONObject.toJSONString(message));
        }

        if (MessageType.GROUP_SIGN_DOWN.equals(message.getType())) {
            // 登出直播间
            Long to = message.getTo();
            log.info("{} Remove {}", ctx.channel().remoteAddress(), to);
            ChannelRepository.removeGroup(to, ctx.channel());
        }

        if (MessageType.STREAMING_HEART.equals(message.getType())) {
            // 直播心跳
            Long channelId = message.getFrom();

            String key = CommonConst.STREAMING_PREFIX + channelId;

            Integer state = RedisUtil.get(key);
            if (state == null) {
                ChannelEntity channelEntity = new ChannelEntity();
                channelEntity.setId(channelId);
                channelEntity.setLiveState(1);
                channelService.updateById(channelEntity);
                RedisUtil.set(key, 1, 30);
            } else {
                RedisUtil.expire(key, 30);
            }
            liveService.updateDuration(channelId);
        }

        log.info("Msg: {}", message);
    }

}
